<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/3/20
 * Time: 11:46
 */

namespace app\queue\refunddealwith;

use app\common\lib\Common;
use app\common\lib\Constant;
use app\common\lib\Guzzle;
use app\common\lib\MoyinTts;
use app\common\lib\Puppeteer;
use app\common\lib\RedisQueue;
use app\common\lib\TencentAsr;
use app\common\lib\TencentIvld;
use app\exception\IndexException;
use app\model\moyin\GenerateTimbreLogModel;
use app\model\novel\NovelChapterPartModel;
use app\model\plan\PromotionPlanModel;
use app\model\redis\RedisQueueModel;
use app\model\user\UserIncomeFlowModel;
use app\model\user\UserInviteRelationModel;
use app\model\user\UserModel;
use app\model\user\UserNovelChapterPartModel;
use app\model\user\UserPointFlowModel;
use app\model\user\UserPromotionPlanModel;
use app\model\user\UserPromotionVideoModel;
use app\model\user\UserRechargeOrderIncomeModel;
use app\model\user\UserRechargeOrderModel;
use app\model\video\AsyncUploadVideoIvldModel;
use support\Cache;
use support\Db;
use Webman\RedisQueue\Consumer;
use app\common\lib\TencentCos;

class RefundDealWith  implements Consumer
{
    // 要消费的队列名
    public $queue = 'refundDealWith';

    // 连接名，对应 plugin/webman/redis-queue/redis.php 里的连接`
    public $connection = 'default';

    protected $resultData = [];

    // 消费
    public function consume($data)
    {
        Common::initQueueConfig();

        $queue = RedisQueueModel::getInstance()->find($data['queueid']);
        $queue->exec_time = date('Y-m-d H:i:s');
        $queue->save();

        try{

            $result = $this->handle($data);

            RedisQueue::getInstance()->saveQueue($this->queue,$data,$result);
        }catch (\Throwable $e){
            RedisQueue::getInstance()->saveQueue($this->queue,$data,['error'=>$e->getMessage()]);
            Common::queueExecptionReport($queue,$data,$e);
        }
    }

    protected function handle($data)
    {
        if(empty($data['order_no'])){
            throw new IndexException(4020,'订单编号为空');
        }
        $where = [
            ['order_no', '=', $data['order_no']],
            ['order_status', '=', Constant::ORDER_STATUS_REFUND],
        ];
        $order = UserRechargeOrderModel::getInstance()->getWhere($where)->first();
        if($order==false){
            throw new IndexException(4020,'订单不存在');
        }

        $this->dealRefundOrderAfterSaveData($order);

        return ['success'];
    }

    protected function dealRefundOrderAfterSaveData($order)
    {
        $userSn = $order['user_sn']??'';
        if($userSn==false){
            throw new IndexException(4020,'用户编号为空');
        }
        $user = UserModel::getInstance()->getWhere(['user_sn'=>$userSn])->first();
        if($user==false){
            throw new IndexException(4020,'用户不存在');
        }

        try{
            Db::connection('mysql')->beginTransaction();
            //todo 1 更新vip用户有效期失效或去掉购买点数
            if($order['product_type']==1){
                $user->vip_expire_time = date('Y-m-d H:i:s',round(time()-5));
                $user->is_vip = 0;
                $user->save();
            }elseif($order['product_type']==2){
                $insert = [
                    'user_sn'=>$userSn,
                    'nums'=>-(round($order['point_nums'])),
                    'type'=>2,
                    'way'=>2,
                    'sourceid'=>$order['id'],
                    'source_table'=>UserRechargeOrderModel::getInstance()->getTable(),
                ];
                UserPointFlowModel::getInstance()->insertGetId($insert);
            }


            //todo 4 给邀请用户分成-返还提成金额
            $parentUserSn = UserInviteRelationModel::getInstance()->getWhere(['invite_user_sn'=>$userSn,'level'=>1])->value('user_sn');
            $parentUser = UserModel::getInstance()->getWhere(['user_sn'=>$parentUserSn])->first();
            //是否已经分过
            $where = [
                'user_sn'=>$parentUserSn,
                'income_source_user_sn'=>$userSn,
                'order_no'=>$order['order_no'],
            ];
            $income = UserRechargeOrderIncomeModel::getInstance()->getWhere($where)->first();

            if($parentUser && $income){
                $insert = [
                    'user_sn'=>$income['user_sn'],
                    'order_no'=>$income['order_no'],
                    'level_type'=>1,
                    'income_source_user_sn'=>$income['income_source_user_sn'],
                    'income_amount'=>-($income['income_amount']),
                    'pay_amount'=>$income['pay_amount'],
                    'pay_time'=>$income['pay_time'],
                    'agent_level'=>$income['agent_level'],
                    'reward_rate'=>$income['reward_rate'],
                    'product_type'=>$income['product_type'],
                    'status'=>2,
                    'settle_time'=>date('Y-m-d H:i:s'),
                ];
                $incomeId = UserRechargeOrderIncomeModel::getInstance()->insertGetId($insert);
                $insertFlow = [
                    'user_sn'=>$income['user_sn'],
                    'amount'=>-($income['income_amount']),
                    'type'=>1,
                    'source_table'=>UserRechargeOrderIncomeModel::getInstance()->getTable(),
                    'sourceid'=>$incomeId,
                    'income_source_user_sn'=>$income['income_source_user_sn'],
                    'income_date'=>date('Y-m-d H:i:s'),
                    'status'=>2,
                    'settle_time'=>date('Y-m-d H:i:s'),
                ];
                UserIncomeFlowModel::getInstance()->insertGetId($insertFlow);
            }
            Db::connection('mysql')->commit();
        }catch (\Exception $e){
            Db::connection('mysql')->rollBack();
            throw $e;
        }catch (\Throwable $e){
            Db::connection('mysql')->rollBack();
            throw $e;
        }

        return true;
    }

    // 消费失败回调
    /*
    $package = [
        'id' => 1357277951, // 消息ID
        'time' => 1709170510, // 消息时间
        'delay' => 0, // 延迟时间
        'attempts' => 2, // 消费次数
        'queue' => 'send-mail', // 队列名
        'data' => ['to' => 'tom@gmail.com', 'content' => 'hello'], // 消息内容
        'max_attempts' => 5, // 最大重试次数
        'error' => '错误信息' // 错误信息
    ]
    */
    public function onConsumeFailure(\Throwable $e, $package)
    {
//        echo "consume failure\n";
//        echo $e->getMessage() . "\n";
//        // 无需反序列化
//        var_export($package);

        RedisQueue::getInstance()->saveQueue($this->queue,$package['data'],['error'=>$e->getMessage()]);
    }

}